import $api from "@/api/index.js"
import $i18n from "@/utils/i18n.js" // 多语言
export default {
	showLoading(title = $i18n.tc('util.loading'),mask = true){
		uni.showLoading({
			title,
			mask
		})
	},
	go( url, param = {}){
		let {
			type = 'page',
			login = false,
			device,
			path = '/pages/',
			is_tips = true
		} = param
		
		if(!url){
			return false;
		}
		// url必须存在
		if(login && !uni.getStorageSync('authToken')){
			this.checkLogin(true);
			return false;
		}
		
		// 判断设备
		if(device){
			let sysInfo = uni.getSystemInfoSync();
			let userclient = sysInfo.uniPlatform;
			if(device == 'h5' && device != sysInfo.uniPlatform){
				this.showToast($i18n.tc("util_go.limit-h5"))
				return false;
			}
			if(device == 'app' && device != sysInfo.uniPlatform){
				this.showToast($i18n.tc("util_go.limit-app"))
				return false;
			}
			if(device == 'mp-weixin' && device != sysInfo.uniPlatform){
				this.showToast($i18n.tc("util_go.limit-mini"))
				return false;
			}
		}
		
		switch (type){
			case 'link':
				this.openUrl(url, is_tips);
				break;
			default:
				uni.navigateTo({
					url: path+url
				});
				break;
		}
		
		return true;
	},
	openUrl(url, tips = true){
		if(tips){
			uni.showModal({
				title: $i18n.tc('util_openurl.title'),
				content:$i18n.tc("util_openurl.content"),
				success: function (res) {
					if (res.confirm) {
						// #ifdef H5
						window.open(url);
						// #endif
						// #ifdef APP-PLUS
						plus.runtime.openURL(url);
						// #endif
						
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		}else{
			// #ifdef H5
			window.open(url);
			// #endif
			// #ifdef APP-PLUS
			plus.runtime.openURL(url);
			// #endif
		}
	},
	redirectGo(url,path = '/pages/'){
		uni.redirectTo({
			url: path+url
		});
	},
	checkLogin($jump = false,login_tips = $i18n.tc("app.login-required")){
		if(!uni.getStorageSync('authToken')){
			if($jump){
				this.showToast(login_tips,function(){
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/auth/login'
						});
					}, 1000);
				});
			}
		}
		return true;
	},
	showToast: function(msg,callback = function(){},icon = 'none'){
		uni.showToast({
			title: msg,
			icon: icon,
			position:'bottom',
			complete:function(e){
				// 执行callback
				setTimeout(() => {
					callback()
				}, 1500)
			}
		});
		this.hideAll()
	},
	// 清除缓存
	// clearCache(clearLogin = false){
	// 	var cacheKeys = [];
	// 	uni.getStorageInfo({
	// 		success: function (res) {
	// 			cacheKeys = res.keys;
	// 		}
	// 	});
	// 	var retain = ['_config','UNI_LOCALE'];
	// 	if(!clearLogin){
	// 		retain.push('__DC_STAT_UUID');
	// 		retain.push('userInfo');
	// 		retain.push('authToken');
	// 	}
	// 	for (let key in cacheKeys) {
	// 		let a = retain.indexOf(cacheKeys[key]);
	// 		if(a == '-1'){
	// 			// 清除缓存
	// 			uni.removeStorageSync(cacheKeys[key]);
	// 		}
	// 	}
	// 	return true;
	// },
	// // 添加缓存
	// addCache(key,value,param = {}){
	// 	let {
	// 		is_user = false
	// 	} = param
	// 	let userInfo = uni.getStorageSync('userInfo');
	// 	if(is_user && userInfo){
	// 		key = userInfo.uid+'_'+key
	// 	}
		
	// 	try {
	// 		uni.setStorageSync(key,value);	
	// 	} catch (e) {
	// 		console.log('数据缓存失败：'+e)
	// 	}
	// 	// console.log(uni.getStorageSync(key))
		
	// },
	// // 获取缓存
	// getCache(key,param = {}){
	// 	let {
	// 		is_user = false
	// 	} = param
	// 	let userInfo = uni.getStorageSync('userInfo');
	// 	if(is_user && userInfo){
	// 		key = userInfo.uid+'_'+key
	// 	}
	// 	try {
	// 		return uni.getStorageSync(key)
	// 	} catch (e) {
	// 		console.log('缓存获取失败：'+e)
	// 	}
	// },
	//深拷贝
	deepCopy(o) {
		let that = this;
		if (o instanceof Array) {
			var n = [];
			for (var i = 0; i < o.length; ++i) {
				n[i] = that.deepCopy(o[i]);
			}
			return n;
		} else if (o instanceof Function) {
			var n = new Function("return " + o.toString())();
			return n
		} else if (o instanceof Object) {
			var n = {}
			for (var i in o) {
				n[i] = that.deepCopy(o[i]);
			}
			return n;
		} else {
			return o;
		}
	},
	hideAll() {
		uni.hideLoading();
		uni.stopPullDownRefresh();
		uni.hideNavigationBarLoading();
	},
	handleStr(str,x,y,z,j){
		if(str.indexOf("[x]") != -1){
			str = str.replace('[x]',x)
		}
		if(str.indexOf("[y]") != -1){
			str = str.replace('[y]',y)
		}
		if(str.indexOf("[z]") != -1){
			str = str.replace('[z]',z)
		}
		if(str.indexOf("[j]") != -1){
			str = str.replace('[j]',j)
		}
		return str;
	},
	getQueryString(name) {
		let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
		let r = window.location.search.substr(1).match(reg);
		if (r !== null) return unescape(r[2]);
		return null;
	},
	// 获取验证码
	smsCode(mobile,type = ''){
		this.showLoading('正在发送')
		let res = $api.user.getSms({mobile:mobile,type:type})
		if(res.code == 200){
			this.showToast('发送成功')
			this.hideAll()
		}
	},
	goNavigateBack(url = '/pages/my/my',time = 1000){
		var pages = getCurrentPages(); // 获取栈实例
		if(pages.length > 1){
			setTimeout(() => {
				uni.navigateBack();
			}, time)
		}else{
			setTimeout(() => {
				uni.switchTab({
					url: '/pages/my/my'
				});
			}, time)
		}
	},
	async copyText(Text){
		if(Text){
			let thos = this
			uni.setClipboardData({
				data: Text.toString(),
				success: function () {
					uni.showToast({
						title:"复制成功",
						icon:'success'
					})
				},
				fail:function(){
					thos.showToast('复制失败：'+Text.toString())
				}
			});
		}
	},
	clearCache(clearLogin = false){
		var cacheKeys = [];
		uni.getStorageInfo({
			success: function (res) {
				cacheKeys = res.keys;
			}
		});
		var retain = ['configInfo','UNI_LOCALE'];
		if(!clearLogin){
			retain.push('__DC_STAT_UUID');
			retain.push('userInfo');
			retain.push('authToken');
		}
		for (let key in cacheKeys) {
			let a = retain.indexOf(cacheKeys[key]);
			if(a == '-1'){
				// 清除缓存
				uni.removeStorageSync(cacheKeys[key]);
			}
		}
	},
	async chooseImage(url = '',count = 1,sourceType = ['album','camera']){
		let [res_upload, {
			tempFiles = [],
			tempFilePath = ''
		}] = await uni.chooseImage({
			count: count,
			sourceType: sourceType
		})
		this.showLoading($i18n.tc('app.uploading'))
		// 支持多图上传
		let uploads = [];
		for (const key in tempFiles) {
			let res = await $api.base.uploadFile({
				filePath: tempFiles[key].path,
				filetype: 'image'
			},url)
			let data = JSON.parse(res)
			if(data.code == 200){
				uploads.push(data.data.url);
			}
		}
		return uploads.length >= 1 ? uploads : null;
	},
	async chooseVideo(){
		
	},
	saveImageToPhoto(imgUrl){
		this.showLoading($i18n.tc('app.saveimg'))
		// #ifdef H5
			this.showToast($i18n.tc('app.upload-fail-h5-tips'))
			return false;
		// #endif
		uni.downloadFile({
			url: imgUrl,
			success: (res) => {
				if (res.statusCode === 200) {
					uni.saveImageToPhotosAlbum({
						filePath:res.tempFilePath,
						success:(res) => {
							this.showToast($i18n.tc('app.save-success'))
						}
					});
				}
			},
			fail:()=>{
				this.showToast($i18n.tc('app.save-fail'))
			}
		});
	},
	getPlatform(){
		let sysInfo = uni.getSystemInfoSync();
		return sysInfo.uniPlatform
	},
	navTitle(){
		let navTitle = document.getElementsByTagName('uni-page-head');
		navTitle[0].style.display = 'none'
	},
	isJSON(str) {
	    if (typeof str == 'string') {
	        try {
	            var obj=JSON.parse(str);
	            if(typeof obj == 'object' && obj ){
	                return true;
	            }else{
	                return false;
	            }
	        } catch(e) {
	            console.log('error：'+str+'!!!'+e);
	            return false;
	        }
	    }
	},
	getTimestamp(){
		let timestamp = new Date().getTime()
		return timestamp
	},
	previewImage(url){
		uni.previewImage({
			urls:[url],
		})
	},
	pageScrollTo(top){
		uni.pageScrollTo({
			scrollTop: 0
		})
	},
	/**
	 * @param {string} key
	 * @param {object} value
	 * @param {number} seconds
	 * @param {bool} is_user
	 */
	setCache(key, value, seconds = null, is_user = false){
		if (!key) {
		    console.log("key不能空");
		    return;
		}
		if(is_user){
			let userInfo = uni.getStorageSync('userInfo');
			if(userInfo){
				key = userInfo.uid+'_'+key
			}
		}
		const obj = {
			data: value
		}
		// value = `${value}`;
		if(seconds){
			const timestamp = Date.parse(new Date()) / 1000;
			// const expire = timestamp + seconds
			obj.expireTime =  timestamp + seconds
			// value = `${value}|${expire}`;
		}
		uni.setStorageSync(key, obj)
	},
	/**
	 * @param {string} key
	 * @param {bool} is_user
	 */
	getCache(key, is_user = false){
		const timestamp = Date.parse(new Date()) / 1000;
		if(is_user){
			let userInfo = uni.getStorageSync('userInfo');
			if(userInfo){
				key = userInfo.uid+'_'+key
			}
		}
		const val = uni.getStorageSync(key);
		if(val.expireTime && timestamp >= val.expireTime){
			console.log("key已失效");
			uni.removeStorageSync(key);
			return
		}
		return val.data
	},
	// 检测是否登录
	// checkLogin(jump = true){
	// 	if(jump){
	// 		setTimeout(() => {
	// 			uni.navigateTo({
	// 				url: '/pages/auth/login'
	// 			});
	// 		}, 1000)
	// 	}
	// }

}